package com.beiing.tianshuai.tianshuai.adapter;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.ImageSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.entity.DynamicDetailBean;
import com.beiing.tianshuai.tianshuai.util.DateUtil;
import com.beiing.tianshuai.tianshuai.util.EmotionUtils;
import com.beiing.tianshuai.tianshuai.util.SPUtils;
import com.beiing.tianshuai.tianshuai.widget.CommentTextView;
import com.qmuiteam.qmui.span.QMUITouchableSpan;
import com.qmuiteam.qmui.widget.textview.QMUISpanTouchFixTextView;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by LZQ on 2017/8/11.
 */

public class CommentReply_RVAdapter extends RecyclerView.Adapter<CommentReply_RVAdapter.mViewHolder> implements View.OnClickListener{

    private OnItemClickListener mOnItemClickListener;
    private TextClickListener mTextClickListener;
    private Context mContext;
    private List<DynamicDetailBean.DataBean.CommentBean.ReplyBean> replyBeanList;
    private LayoutInflater layoutInflater;

    public CommentReply_RVAdapter(Context mContext, List<DynamicDetailBean.DataBean.CommentBean.ReplyBean> replyBeanList) {
        this.mContext = mContext;
        this.replyBeanList = replyBeanList;
        layoutInflater = LayoutInflater.from(mContext);
    }

    @Override
    public mViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = layoutInflater.inflate(R.layout.item_comment_reply, parent, false);
        mViewHolder viewHolder = new mViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(mViewHolder holder, final int position) {
        if (position < 2){
            final int i = replyBeanList.size() - position - 1;
            SpannableStringBuilder spannableString = new SpannableStringBuilder();
            String fName = replyBeanList.get(i).getFName();
            String tName = replyBeanList.get(i).getTName();
            if (!TextUtils.isEmpty(fName)) {
                spannableString.append(fName);
            }
            spannableString.append("回复");
            if (!TextUtils.isEmpty(tName)) {
                spannableString.append(tName);
            }
            spannableString.append(":");
            String contentDecode = null;
            try {
                contentDecode = URLDecoder.decode(replyBeanList.get(i).getContent(), "UTF-8");
                spannableString.append(contentDecode);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            spannableString.append("  " + getTime(replyBeanList.get(i).getCreateTime()));

            //表情拼接
            Resources res = mContext.getResources();
            String regexEmotion = "\\[([\u4e00-\u9fa5\\w+\\.])+\\]";
            Pattern patternEmotion = Pattern.compile(regexEmotion);
            Matcher matcherEmotion = patternEmotion.matcher(spannableString);
            while (matcherEmotion.find()){
                // 获取匹配到的具体字符
                String key = matcherEmotion.group();
                // 匹配字符串的开始位置
                int start = matcherEmotion.start();
                // 利用表情名字获取到对应的图片
                Integer imgRes = EmotionUtils.getImgByName(key);
                if (imgRes != null) {
                    // 压缩表情图片
                    int size = (int) holder.tv_reply.getTextSize() * 13 / 10;
                    Bitmap bitmap = BitmapFactory.decodeResource(res, imgRes);
                    Bitmap scaleBitmap = Bitmap.createScaledBitmap(bitmap, size, size, true);

                    ImageSpan span = new ImageSpan(mContext, scaleBitmap);
                    spannableString.setSpan(span, start, start + key.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
            }

            /** 暂时设置在全部回复页里进行删除 **/
//            if (replyBeanList.get(i).getFormUid().equals(SPUtils.getString(mContext,"uid",null))){
//                spannableString.append("  " + "删除");
//            }

            int fNameLength = TextUtils.isEmpty(fName) ? 0 : fName.length();
            int tNameLength = TextUtils.isEmpty(tName) ? 0 : tName.length();
            int contentLength = contentDecode.length();

            ForegroundColorSpan grayColorSpan = new ForegroundColorSpan(Color.parseColor("#9D9D9D"));
            spannableString.setSpan(grayColorSpan, fNameLength + 2 + tNameLength + 1 + contentLength,
                    spannableString.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

        /*--------设置点击事件-------*/
            spannableString.setSpan(new QMUITouchableSpan(
                    Color.parseColor("#67A0FF"),
                    Color.parseColor("#67A0FF"),
                    Color.parseColor("#00000000"),
                    Color.parseColor("#E0E0E0")) {
                @Override
                public void onSpanClick(View view) {
                    if (mTextClickListener != null){
                        mTextClickListener.onTextClick(view, i ,1);
                    }
                }
            }, 0, fNameLength, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

            spannableString.setSpan(new QMUITouchableSpan(
                    Color.parseColor("#67A0FF"),
                    Color.parseColor("#67A0FF"),
                    Color.parseColor("#00000000"),
                    Color.parseColor("#E0E0E0")) {
                @Override
                public void onSpanClick(View view) {
                    if (mTextClickListener != null){
                        mTextClickListener.onTextClick(view, i, 2);
                    }
                }
            }, 2 + fNameLength, 2 + fNameLength + tNameLength, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

            ClickableSpan dClickableSpan = new ClickableSpan() {
                @Override
                public void onClick(View view) {
                    if (mTextClickListener != null){
                        mTextClickListener.onTextClick(view, i, 3);
                    }
                }
                @Override
                public void updateDrawState(TextPaint ds) {
                    ds.setUnderlineText(false);
                }
            };
            if (replyBeanList.get(i).getFormUid().equals(SPUtils.getString(mContext,"uid",null))){
                spannableString.setSpan(dClickableSpan, spannableString.length() - 2, spannableString.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            }
            holder.tv_reply.setMovementMethodDefault();
            holder.tv_reply.setText(spannableString);
        } else if (position == 2) {
            holder.tv_reply.setText("点击查看更多");
            holder.tv_reply.setTextColor(Color.parseColor("#67A0FF"));
        } else {
            holder.tv_reply.setVisibility(View.GONE);
        }

        holder.tv_reply.setTag(position);
        holder.tv_reply.setOnClickListener(this);
    }

    public void removeItem(int position){
        final int i = replyBeanList.size() - position-1;
        replyBeanList.remove(i);
        notifyItemRemoved(i);
    }
    @Override
    public int getItemCount() {
        return replyBeanList == null ? 0 : replyBeanList.size();
    }

    @Override
    public void onClick(View view) {
        if (mOnItemClickListener != null){
            mOnItemClickListener.onItemClick(view, (int) view.getTag());
        }
    }

    class mViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.tv_reply)
        QMUISpanTouchFixTextView tv_reply;

        public mViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    private String getTime(String timeStamp){
        long publishTime = Long.parseLong(timeStamp);
        long currentTime = new Date().getTime() / 1000;
        long timeDifference = currentTime - publishTime;
        long timeDifferenceHour = timeDifference / 3600;
        if (timeDifference / 60 < 1){
            return "刚刚";
        } else if (timeDifferenceHour < 1){
            return (timeDifference / 60) + "分钟前";
        } else if (timeDifferenceHour < 24){
            return timeDifferenceHour + "小时前";
        } else if (timeDifferenceHour / 24 < 30){
            return (timeDifferenceHour / 24) + "天前";
        } else {
            return DateUtil.getStrTime(timeStamp);
        }
    }

    /**
     * 条目点击事件
     */
    interface OnItemClickListener{
        void onItemClick(View view , int childPosition);
    }

    public void setOnItemClickListener(OnItemClickListener listener){
        this.mOnItemClickListener = listener;
    }

    /**
     * 文本点击事件
     */
    public interface TextClickListener{
        void onTextClick(View view, int childPosition, int tvPosition);
    }

    public void setTextClickListener(TextClickListener listener){
        this.mTextClickListener = listener;
    }

}
